<?php
/*******************************
 * Framework Defines
 */

/****
 * Global Framework DEFINES
 */
if ( !defined('INSTALL_DIR') ) {
        define('INSTALL_DIR', '/usr/www/users/algae/common/version2/');
}
if ( !defined('SMARTY_DIR') ) {
	define('SMARTY_DIR', '/usr/www/users/algae/common/smarty/libs/');
}

require_once(INSTALL_DIR . 'Log.class.php');
require_once('config.inc.php');

/**
 * Included Files
 */
if ( Log::isDebug() ) {
	require_once(SMARTY_DIR . 'Smarty.class.php');
	require_once(INSTALL_DIR . 'DB.class.php');
	require_once(INSTALL_DIR . 'Session.class.php');
} else {
	@require_once(SMARTY_DIR . 'Smarty.class.php');
	@require_once(INSTALL_DIR . 'DB.class.php');
	@require_once(INSTALL_DIR . 'Session.class.php');
}

/****
 * Application DEFINES
 */
if ( !defined('ROOT_PATH') ) {
	Log::fatal('Define application ROOT_PATH');
	echo('Configuration error: see log');
}
if ( !defined('FILENAME') ) {
        define('FILENAME', $_SERVER['PHP_SELF']);
}
if ( !defined('SITE_TITLE') ) {
	Log::fatal('Define application TITLE');
        define('SITE_TITLE', 'greenalgae.net');
}
if ( !defined('SESSION_NAME') ) {
	Log::fatal('Define SESSION_NAME');
	echo('Configuration error: see log');
}
if ( !defined('TEMPLATE_ROOT_DIR') ) {
	Log::fatal('Define application TEMPLATE_ROOT_DIR');
	echo('Configuration error: see log');
}
if ( !defined('TEMPLATE_COMPILE_DIR') ) {
	Log::fatal('Define application TEMPLATE_COMPILE_DIR');
	echo('Configuration error: see log');
}
//TEMPLATE_PLUGIN_DIR
//TEMPLATE_CACHE_DIR
if ( !defined('TEMPLATE_DEFAULT') ) {
        define('TEMPLATE_DEFAULT', 'default.html');
}
if ( !defined('LOGOUT_FORWARD_URL') ) {
        define('LOGOUT_FORWARD_URL', '/index.php');
}



if ( !defined('AUTH_OK_MESSAGE') ) {
        define('AUTH_OK_MESSAGE', 'Login Successful');
}
if ( !defined('AUTH_PERM_MESSAGE') ) {
        define('AUTH_PERM_MESSAGE', 'You have insufficent permissions to access this page');
}
if ( !defined('AUTH_FAILED_MESSAGE') ) {
        define('AUTH_FAILED_MESSAGE', 'You have entered an invalid login/password combination');
}
if ( !defined('AUTH_NONE_MESSAGE') ) {
        define('AUTH_NONE_MESSAGE', 'Please enter a valid login/password combination');
}
if ( !defined('AUTH_USERS_TABLE') ) {
        define('AUTH_USERS_TABLE', 'users');
}
if ( !defined('AUTH_LOGOUT_BUTTON') ) {
	//Logout text or image
        define('AUTH_LOGOUT_BUTTON', '[logout]');
}
if ( !defined('AUTH_LOGIN_BUTTON') ) {
	//Login image or text determined by AUTH_LOGIN_X
        define('AUTH_LOGIN_BUTTON', 'login');
}
if ( !defined('AUTH_CODE_IMAGE_WIDTH') ) {
	//width of AUTH_LOGIN image
        define('AUTH_CODE_IMAGE_WIDTH', 0);
}
if ( !defined('AUTH_CODE_IMAGE_HEIGHT') ) {
	//height of AUTH_LOGIN image
        define('AUTH_CODE_IMAGE_HEIGHT', 0);
}
if ( !defined('AUTH_CODE_IMAGE_FILE') ) {
        define('AUTH_CODE_IMAGE_FILE', '/auth_code.php');
}
if ( !defined('AUTH_CODE_ENABLE') ) {
        define('AUTH_CODE_ENABLE', false);
}
if ( AUTH_CODE_ENABLE == true ) {
        define('SESSION_CODE', true);
}


define('AUTH_OK', 4);
define('AUTH_PERMISSION', 3);
define('AUTH_FAILED', 2);
define('AUTH_NONE', 1);
define('AUTH_PUBLIC', 0);

/**
 * Abstract Framework Class
 *
 */
abstract class Framework extends Smarty
{
	private $_session;
	private $_db;
	private $_INIT = Array();
	private $_PARAMS = Array();

	/**
	 * Framework Modules need to provide implementations for these methods
	 * Handle standard unauthenicated request
	 */
	abstract protected function handleRequest();
	abstract protected function handleCommon();

	/**
	 * Page factory
	 */
	final public static function open(array $INIT, array $PARAMS=Array()) {
		$module = new $INIT['MODULE']($INIT, $PARAMS);
		$module->preHandle();
		$module->handleRequest();
		$module->postHandle();
	}

	public function __construct(array $init, array $params) {
		Log::debug('Constructing Framework');
		$this->_INIT = $init;
		$this->_PARAMS = $params;

		if ( !isset($this->_INIT['TEMPLATE_DEFAULT']) ) {
			$this->_INIT['TEMPLATE_DEFAULT'] = TEMPLATE_DEFAULT;
		}

		$this->template_dir	= TEMPLATE_ROOT_DIR;
		$this->compile_dir	= TEMPLATE_COMPILE_DIR;
		$this->plugins_dir[]	= INSTALL_DIR . 'plugins/';

		if ( defined(TEMPLATE_PLUGIN_DIR) ) {
			$this->plugins_dir[]	= TEMPLATE_PLUGIN_DIR;
		}
		if ( defined(TEMPLATE_CONFIG_DIR) ) {
			$this->config_dir = TEMPLATE_CONFIG_DIR;
		}
		if ( defined(TEMPLATE_CACHE_DIR) ) {
			$this->caching = false;
			$this->cache_dir = TEMPLATE_CACHE_DIR;
		}

		self::register_block('results', 'smarty_block_results', false);
	}

	public function __destruct() {
	}

	final public function getVar($key) {
		return $this->_session->getVar($key);
	}

	final public function setParameter($key, $value) {
		$this->_PARAMS[$key] = $value;
	}

	final public function getParameter($key) {
		return $this->_PARAMS[$key];
	}

	final public function getInitialization($key) {
		return $this->_INIT[$key];
	}

	final public function register($key, $var) {
		$this->_session->register($key, $var);
	}

	final public function unregister($key) {
		$this->_session->unregister($key);
	}
	
	final public function db() {
		return $this->_db;
	}

	/**
	 * Executes code before page is rendered
	 *  - connects to database
	 *  - initializes or reestablishes sessions
	 *  - handles page authorization if required
	 * returns false : no authorization
	 *         true  : sufficient authorization
	 */
	final private function preHandle() {
		Log::debug('calling Framework::preHandle');

        	/**************************************************
        	 * Sets Database Connection
        	 */
		$this->_db = Database::create(DATABASE);
                if ( !$this->_db->isConnected() ) {
			Log::fatal('Database connection failure');
			Framework::handleError('framework/db_error.html');
                       	exit;
        	}

		/**************************************************
        	 * Session
        	 */
		$this->_session = Session::create(SESSION_NAME, $this->_db);
		if ( $this->_session == null ) {
			Framework::handleError('framework/session_error.html');
		}

		$this->_session->start();
		if ( isset($_GET['kill']) ) {
			$this->_session->kill();
			Framework::handleForward(LOGOUT_FORWARD_URL);
			unset($this->_session);
		} else if ( isset($_GET['logout']) ) {
			//$this->_session->logout();
			Framework::logout();	
		}
		
		$this->handleCommon();
	}

	/**
	 * Executes code after page is rendered
	 */
	final private function postHandle($display=true) {
		Log::debug('calling Framework::postHandle');

		$this->_PARAMS['SITE_TITLE'] = SITE_TITLE; 

		$this->_PARAMS['LOGOUT_URL'] = '?logout=' . $this->_session->getSessionId();
		$this->_PARAMS['LOGIN_URL'] =  '?login=' . $this->_session->getSessionId();
		$this->_PARAMS['KILL_URL'] = '?kill=' . $this->_session->getSessionId();

		Framework::assign('PARAMS', $this->_PARAMS);
		Framework::assign('SESSION', $this->_session->getVars());
		$this->_session->freeze();

		if ( $display ) {
			Framework::display($this->_INIT['TEMPLATE_DEFAULT']);
			if ( Log::isDebug() ) {
				self::printEnvironment();
			}
		}
		exit;	
	}

	/**
	 * Forwards to new page
	 */
	final private function handleForward($url, $msg='') {
		$this->_session->freeze();
		header("Location: $url");
		echo($msg);
		exit;
	}

	/**
	 * Handles Standardized Errors
	 */
	final private function handleError($assign) {
		$this->_PARAMS['content'] = $assign;
		Framework::postHandle();
		/*
		if ( defined('SESSION_NAME') && isset($this->_session) ) {
			$this->_session->freeze();
		}
		Framework::display($this->_INIT['TEMPLATE_DEFAULT']);
		*/
		exit;
	}

	/**
	 * Echo Framework Environment
	 */
	final private function printEnvironment() {
		echo('<p>' . date('D M j H:i:s T Y') );

                echo ('<p>PARAMS ENVIRONMENT<br>');
                foreach( $this->_PARAMS as $key => $val ) {
                        switch ( $key ) {
                        case 'DATABASE':
                                $val = 'hidden';
                                break;
                        default:
                                break;
                        }
                        echo nl2br("$key: $val\n");
                }

                echo ('<p>SESSION VARIABLES<br>');
		foreach( $this->_session->getVars() AS $key => $val ) {
                        echo nl2br("$key: $val\n");
                }

                echo ('<p>COOKIE ENVIRONMENT<br>');
                foreach( $_COOKIE as $key => $val ) {
                        echo nl2br("$key: $val\n");
                }

                echo ('<p>GET VARIABLES<br>');
                foreach( $_GET as $key => $val ) {
                        if ( is_array($val) ) {
                                foreach( $val AS $key2=>$val2 )
                                        echo nl2br("$key-&gt;$key2: $val2\n");
                        } else {
                                echo nl2br("$key: $val\n");
                        }
                }

                echo ('<p>POST VARIABLES<br>');
                foreach( $_POST as $key => $val ) {
                        if ( is_array($val) ) {
                                foreach( $val AS $key2=>$val2 )
                                        echo nl2br("$key-&gt;$key2: $val2\n");
                        } else {
                                echo nl2br("$key: $val\n");
                        }
                }

                echo ('<p>SERVER ENVIRONMENT<br>');
                foreach( $_SERVER as $key => $val ) {
                	if ( is_array($val) ) {
                		foreach( $val AS $key2=>$val2 )
                        		echo nl2br("$key-&gt;$key2: $val2\n");
                	} else {
                        	echo nl2br("$key: $val\n");
                	}
		}
	}
}

?>
